package com.k.leetcode.addtwonumbers;

/**
 * 链表加法
 l1:ListNode{val=2, next=ListNode{val=4, next=ListNode{val=3, next=null}}}
 l2:ListNode{val=5, next=ListNode{val=6, next=ListNode{val=4, next=null}}}
 lZ:ListNode{val=7, next=ListNode{val=0, next=ListNode{val=8, next=null}}}
 * @author k
 */
public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null) {p = p.next;}
            if (q != null) {q = q.next;}
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

    /**
     * 链表翻转
     * @param node node
     * @return reverseNode
     */
    public ListNode reverse(ListNode node){
        ListNode prev = null;
        while(node!=null){
            ListNode tmp = node.next;

            node.next = prev;
            prev = node;

            node = tmp;
            System.out.println("reverse itm:"+prev);
        }
        return prev;
    }


    public static void main(String[] args) {
        AddTwoNumbers m = new AddTwoNumbers();
        ListNode l1 = new ListNode(2);
        l1.next=new ListNode(4);
        l1.next.next = new ListNode(3);
        l1.next.next.next = new ListNode(9);
        System.out.println("l1:"+l1);
        System.out.println("reverseNode:" + m.reverse(l1));


        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        System.out.println("l2:"+l2);

        ListNode lz = m.addTwoNumbers(l1,l2);
        System.out.println(lz);
        for(int i=1;i<=101;i++){
            System.out.println(i+"/"+2+"="+i/2);
        }
    }
}

/**
 {
    val:2,
    next:{
        val:4,
        next:{
            val:3,
            next:null
        }
    }
 }
 */
 class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
